package cn.hj.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import cn.hj.basic.constant.BaseConstant;
import cn.hj.basic.dto.BinderDto;
import cn.hj.basic.dto.LoginDto;
import cn.hj.basic.dto.UserDto;
import cn.hj.basic.exception.BusinessException;
import cn.hj.basic.service.impl.BaseServiceImpl;
import cn.hj.basic.util.AjaxResult;
import cn.hj.basic.util.HttpClientUtils;
import cn.hj.basic.util.MD5Utils;
import cn.hj.basic.util.StrUtils;
import cn.hj.user.domain.Logininfo;
import cn.hj.user.domain.User;
import cn.hj.user.domain.WxUser;
import cn.hj.user.mapper.LogininfoMapper;
import cn.hj.user.mapper.UserMapper;
import cn.hj.user.mapper.WxUserMapper;
import cn.hj.user.service.ILogininfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 账号密码登录
     * @param dto
     * @return
     */
    @Override
    public Map<String,Object> acountLogin(LoginDto dto) {

        //判断是否为空
        if(StringUtils.isEmpty(dto.getUsername())
                || StringUtils.isEmpty(dto.getPassword())
                ||dto.getType()==null){
            throw new BusinessException("参数不能为空");
        }
        //查询手机号是否存在
        Logininfo logininfo = logininfoMapper.loadByUsername(dto);
            if (logininfo==null){
            throw new BusinessException("账号不存在，请先注册账号");
        }
       /* //判断密码是否一致
        String salt = dto.getPassword()+logininfo.getSalt();
        String md5Passwprd = MD5Utils.encrypByMd5(salt);
        if (!md5Passwprd.equals(logininfo.getPassword())){
            throw new BusinessException("密码错误");
        }*/
        //登录成功后存redis
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        //返回登录成功的信息
        HashMap<String,Object> map = new HashMap<>();
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("token",token);
        map.put("logininfo",logininfo);
        return map;
    }


    /**
     * 微信扫码登录
     * @param param
     */
    @Override
    public AjaxResult wechat(String code) {
        //先判断code是否为空
        if (StringUtils.isEmpty(code)){
            throw new BusinessException("参数错误");
        }
        //发送请求去拿token和openid（这里使用的是工具类）
        String  toKenUrl= BaseConstant.WXUSER_GET_TOKEN_URL
                .replace("APPID",BaseConstant.APPID)
                .replace("SECRET",BaseConstant.SECRET)
                .replace("CODE",code);
        String toKenObjStr = HttpClientUtils.httpGet(toKenUrl);
        //使用阿里提供的json转换工具
        JSONObject jsonObject = JSONObject.parseObject(toKenObjStr);
        String accessToken = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");
        //去查用户是否已经注册过
        WxUser wxUser = wxUserMapper.loadByOpenId(openId);
        //如果wx表里书记存在，并且user_id存在，说明微信注册过，直接免密登录（验证user_id不为空是为了排除脏数据）
        if (wxUser!=null && wxUser.getUser_id()!=null){
            //登录成功后存redis
            String token = UUID.randomUUID().toString();
            //通过user_id，查询loginfo表(需要返回一个logininfo数据)
            Logininfo logininfo = logininfoMapper.loadByUserId(wxUser.getUser_id());
            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
            //返回登录成功的信息
            HashMap<String,Object> map = new HashMap<>();
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            map.put("token",token);
            map.put("logininfo",logininfo);
            return AjaxResult.newAjaxResult().setResultObj(map);
        }else{
            //如果用户没有微信注册过，要跳到微信绑定页面，带上accessToken和openId返回给前端
            String binderParams = "?accessToken="+accessToken+"&openId="+openId;
            return AjaxResult.newAjaxResult().setSuccess(false).setResultObj(binderParams);
        }
    }

    /**
     * 微信绑定业务
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> binderWechat(BinderDto dto) {
        String accessToken = dto.getAccessToken();
        String openId = dto.getOpenId();
        String verifyCode = dto.getVerifyCode();
        String phone = dto.getPhone();
        //手机号，验证码，token令牌，openId都不能为空
        if (StringUtils.isEmpty(accessToken)
                || StringUtils.isEmpty(openId)
                || StringUtils.isEmpty(verifyCode)
                || StringUtils.isEmpty(phone)) {
            throw new BusinessException("请填写好注册内容");
        }
        //判断验证码是否过期
        String key = BaseConstant.BUSINESS_binder_REGISTER + phone;
        Object codeTmp = redisTemplate.opsForValue().get(key);
        if (codeTmp == null) {
            throw new BusinessException("验证码已失效请重写获取");
        }
        //判断验证码是否正确
        String code = ((String) codeTmp).split(":")[0];
        Logininfo logininfo = null;
        if (!verifyCode.equalsIgnoreCase(code)) {
            throw new BusinessException("验证码错误，请重写输入");
        }
        //查询手机是否注册过
        User user = userMapper.loadByPhone(phone);
        //手机已被注册，查询出用户做微信绑定
        if (user != null) {
             logininfo = logininfoMapper.loadByUserId(user.getId());
        } else {
            //手机没有被注册过，生成新的
            //转类型
            User user1 = dto2User(phone);
            logininfo = dto2Logininfo(user1);
            //保存数据先保存存loginifo,返回自增id,才存user表
            logininfoMapper.insert(logininfo);
            user1.setLogininfo_id(logininfo.getId());
            userMapper.insert(user1);
        }
        //调用微信查询用户的信息
        String replace = BaseConstant.WXUSER_GET_URL.replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String wxUserStr = HttpClientUtils.httpGet(replace);
        WxUser wxUser = JSONObject.parseObject(wxUserStr, WxUser.class);
        wxUser.setUser_id(user.getId());
        wxUserMapper.insert(wxUser);
        //登录成功后存redis
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        //返回登录成功的信息
        HashMap<String,Object> map = new HashMap<>();
        logininfo.setSalt(null);
        map.put("token",token);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;

    }
    private User dto2User (String phone){
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        //设置盐值
        String slat = StrUtils.getComplexRandomString(32);
        user.setSalt(slat);
        //加密(这里要生成默认密码，我用123456）可以发短信告诉客户
        String md5 = MD5Utils.encrypByMd5("123456" + slat);
        user.setPassword(md5);
        return user;
    }

    private Logininfo dto2Logininfo (User user){
        Logininfo logininfo = new Logininfo();
        //通明拷贝
        BeanUtils.copyProperties(user, logininfo);
        return logininfo;
    }
}
